
#include <iostream>
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <sys/ioctl.h>
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */


#include <QWidget>
#include <QtDebug>

#include "SerialWidget.h"
using namespace std;

SerialWidget::SerialWidget(QWidget *parent) : QWidget(parent) {
    int fd1;
    fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_SYNC);
    if(fd==-1){
        qDebug()<< "Open_port: Unable to open /dev/ttyUSB0";
    }

    setBaudRate(fd);
}

void SerialWidget::setBaudRate(int fd)
{

    struct termios options;
    /*
     * Get the current options for the port...
     */

    tcgetattr(fd, &options);

    /*
     * Set the baud rates to 19200...
     */

    cfsetispeed(&options, B115200);
    cfsetospeed(&options, B115200);

    /*
     * Enable the receiver and set local mode...
     */

    options.c_cflag |= (CLOCAL | CREAD | CSTOPB);

    /*
     * Set the new options for the port...
     */

    tcsetattr(fd, TCSANOW, &options);



        return;
}

SerialWidget::~SerialWidget()
{
    //close(fd);

    return;
}

void SerialWidget::sendCommand(QString command)
{
    char c = 13 ;
    write(fd,command.toAscii(),command.length());
    write(fd,&c,1);

}

void SerialWidget::receiveStatus()
{
    char c;
    read(fd,&c,1);

    if(c=='o')
    {
        for(int i=1;c!=13;i++)
        {
            read(fd,&c,1);
            //qDebug()<<c;
        }
        correctCommands = correctCommands + 1;
    }
    if(c=='e')
    {
        incorrectCommands = incorrectCommands + 1;
        for(int i=1;c!=13;i++)
        {
            read(fd,&c,1);
            qDebug()<<c;
        }
    }


}
